package cz.cuni.amis.pogamut.episodic.query;

import cz.cuni.amis.pogamut.episodic.memory.AgentMemory;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author Miso
 */
public class QueryModule {
    AgentMemory mem;

    private ComboTexts comboTexts;

    protected QueryExecutor executor;

    final JComboBox mainCombo = new JComboBox();
    final JComboBox secondaryCombo = new JComboBox();

    public static class MainComboListener implements ActionListener {
        final QueryModule q;
        public MainComboListener(QueryModule q) {
            this.q = q;
        }
        public void actionPerformed(ActionEvent e) {
            JComboBox cb = (JComboBox)e.getSource();
            int selected = cb.getSelectedIndex();
            q.comboTexts.mainComboSelected = selected;
            q.updateSecondaryCombo();
        }
    }
    public static class ButtonListener implements ActionListener {
        final QueryModule q;
        public ButtonListener(QueryModule q) {
            this.q = q;
        }
        public void actionPerformed(ActionEvent e) {
            ComboTexts.ComboString cs = q.comboTexts.secondaryComboStrings.get(q.secondaryCombo.getSelectedIndex());
            q.text.setText(q.executor.executeQuery(cs.type, cs.usual, cs.str));
        }
    }

    TextArea text;

    public QueryModule(AgentMemory mem) {
        this.mem = mem;
        comboTexts = new ComboTexts(mem);
        executor = new QueryExecutor(mem);

        final JFrame frame = new JFrame();

        for (String s : comboTexts.getMainComboTexts()) {
            mainCombo.addItem(s);
        }
        mainCombo.addActionListener(new MainComboListener(this));
        comboTexts.mainComboSelected = 0;
        for (String s : comboTexts.getSecondaryComboTexts()) {
            secondaryCombo.addItem(s);
        }

        final JPanel panel = new JPanel();
        frame.getContentPane().add(panel);
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.add(mainCombo);
        panel.add(secondaryCombo);

        final JButton button = new JButton("Execute Query");
        button.addActionListener(new ButtonListener(this));
        panel.add(button);

        text = new TextArea("", 20, 80, TextArea.SCROLLBARS_BOTH);
        panel.add(text);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        frame.toFront();
    }

    public void updateSecondaryCombo() {
        secondaryCombo.removeAllItems();
        for (String s : comboTexts.getSecondaryComboTexts()) {
            secondaryCombo.addItem(s);
        }
    }


}
